import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus';
/**
 * @description 添加单位
 * @param {String | Number} value 值 100
 * @param {String} unit 单位 px em rem
 */
export const addUnit = (value : string | number, unit = 'px') => {
  return !Object.is(Number(value), NaN) ? `${value}${unit}` : value
}

/**
 * @description 树转数组，队列实现广度优先遍历
 * @param {Array} data  数据
 * @param {Object} props `{ children: 'children' }`
 */

export const treeToArray = (data : any[], props = { children: 'children' }) => {
  data = JSON.parse(JSON.stringify(data))
  const { children } = props
  const newData = []
  const queue : any[] = []
  data.forEach((child : any) => queue.push(child))
  while (queue.length) {
    const item : any = queue.shift()
    if (item[children]) {
      item[children].forEach((child : any) => queue.push(child))
      delete item[children]
    }
    newData.push(item)
  }
  return newData
}

/**
 * @description 获取正确的路经
 * @param {String} path  数据
 */
export function getNormalPath(path : string) {
  if (path.length === 0 || !path || path == 'undefined') {
    return path
  }
  const newPath = path.replace('//', '/')
  const length = newPath.length
  if (newPath[length - 1] === '/') {
    return newPath.slice(0, length - 1)
  }
  return newPath
}


const setColors = () => {
  const a = [
    { text: '#4F2DFC', bg: '#EDEAFF' },
    { text: '#ED44F5', bg: '#FDECFE' },
    { text: '#11B455', bg: '#E7F7EE' },
    { text: '#FF9002', bg: '#FFF4E5' },
    { text: '#03ABAD', bg: '#E5F6F7' },
    { text: '#216FFF', bg: '#E8F0FF' },
    { text: '#FF5F5F', bg: '#FFEFEF' },
    { text: "hsl(200, 100%, 58%)", bg: "hsl(200, 100%, 96%)" },
    { text: "hsl(140, 70%, 60%)", bg: "hsl(140, 70%, 96%)" },
    { text: "hsl(240, 70%, 50%)", bg: "hsl(240, 70%, 96%)" },
    { text: "hsl(330, 100%, 55%)", bg: "hsl(330, 100%, 96%)" },
    { text: "hsl(10, 100%, 52%)", bg: "hsl(10, 100%, 96%)" },
    { text: "hsl(30, 100%, 54%)", bg: "hsl(30, 100%, 96%)" },
    { text: "hsl(153, 100%, 56%)", bg: "hsl(153, 100%, 96%)" },
    { text: "hsl(224, 100%, 58%)", bg: "hsl(224, 100%, 96%)" },
    { text: "hsl(320, 100%, 58%)", bg: "hsl(320, 100%, 96%)" },
    { text: "hsl(250, 100%, 58%)", bg: "hsl(250, 100%, 96%)" },
    { text: "hsl(300, 100%, 60%)", bg: "hsl(300, 100%, 96%)" },
  ];
// 明确指定变量b的类型为包含和数组a相同元素类型的数组
let b: { text: string; bg: string; }[] = []
  for(let i = 0; i < 10; i++){
    b = b.concat(a)
  };
  return b
}
// 颜色
export const colors = setColors();
export const copy = (textToCopy : string, tips:string = '复制成功') => {
  return new Promise<void>((resolve, reject) => {
    // 尝试使用 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(textToCopy).then(() => {
        ElMessage.success(tips)
        resolve();
      }).catch((error) => {
        console.log(error)
        ElMessage.error('Clipboard API 复制失败')
        fallbackMethod(textToCopy).then(resolve).catch(reject);
      });
    } else {
      // 如果 Clipboard API 不可用，则回退到 execCommand 方法
      fallbackMethod(textToCopy).then(resolve).catch(reject);
    }
  });
};

// 回退方法：使用 document.execCommand('copy')
function fallbackMethod(textToCopy : string) {
  return new Promise<void>((resolve, reject) => {
    try {
      const tempTextarea = document.createElement('textarea');
      tempTextarea.value = textToCopy;
      tempTextarea.style.position = 'fixed';
      tempTextarea.style.top = '0';
      tempTextarea.style.left = '0';
      tempTextarea.style.opacity = '0';

      document.body.appendChild(tempTextarea);
      tempTextarea.select();
      tempTextarea.setSelectionRange(0, tempTextarea.value.length);

      const result = document.execCommand('copy');
      if (result) {
        alert('已复制到剪贴板！');
        document.body.removeChild(tempTextarea);
        resolve();
      } else {
        throw new Error('execCommand 复制失败');
      }
    } catch (error) {
      console.error('回退方法复制失败:', error);
      reject(error);
    }
  });
}

export const getBodyW = () => {
  return window.innerWidth < 770 ? true : false
};
export const isMobile = window.innerWidth < 770 ? true : false;
// 下载图片
export const downImage = (imageSrc:string) => {
  const link = document.createElement('a');
  link.href = imageSrc;
  link.download = `下载`; // 设置下载文件名
  // 触发下载
  document.body.appendChild(link);
  link.click();
  // 移除临时 <a> 标签
  document.body.removeChild(link);
}
// 颜色处理
export const rgbToHsl = (hex : string) => {
  let bigint = parseInt(hex.slice(1), 16);
  let r = (bigint >> 16) & 255;
  let g = (bigint >> 8) & 255;
  let b = bigint & 255;

  r /= 255, g /= 255, b /= 255;

  const max = Math.max(r, g, b), min = Math.min(r, g, b);
  let h, s, l = (max + min) / 2;

  if (max == min) {
    // 灰色：无色调
    h = s = 0;
  } else {
    let d = max - min;
    // 饱和度取决于亮度是小于或大于0.5
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break;
      case g: h = (b - r) / d + 2; break;
      case b: h = (r - g) / d + 4; break;
    }
    // 确保h在使用前已定义
    if (typeof h!== 'undefined') {
      h /= 6;
    }
  }
  // 确保 h 已定义，若未定义则设为 0
  if (typeof h === 'undefined') {
    h = 0;
  }
  return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)];
}

export const imageJson = [
  {id:2, title:'内容', val:'', key:'text', example:''},
  {id:5, title:'分辨率', val:'', key:'dpi', example:'', choose:['512x512', '640x360', '640x480', '640x640', '680x512', '512x680', '768x768', '720x1280', '1280x720','1024x1024']},
]
// 类型:0 - 图片， 1文本 2多行文本 3 单选4 多选 5下拉选择 6-地址选择， 7-日期
export const jobJson = [
  {id:1, title:'岗位名称', val:'', key:'job_name', example:''},
  {id:2, title:'岗位描述', val:'', key:'job_description', example:''},
  {id:5, title:'学历要求', val:'', key:'education_requirements', example:'', choose:['小学', '中学', '大专', '本科', '硕士', '博士']},
  {id:5, title:'年龄要求', val:'', key:'age_requirements', example:''},
  {id:5, title:'工作时间', val:'', key:'working_hours', example:''},
  {id:5, title:'经验要求', val:'', key:'experience_requirements', example:''},
  {id:6, title:'工作地址', val:'', key:'job_address', example:''},
  {id:5, title:'岗位薪资', val:'', key:'salary', example:''},
  {id:5, title:'结算方式', val:'', key:'settlement_method', example:''},
  {id:5, title:'招聘企业', val:'', key:'recruiting_company', example:''},
  {id:5, title:'营业执照', val:'', key:'business_license_image', example:''},
  {id:5, title:'法人身份证', val:'', key:'legal_person_id_card_images', example:''},
  {id:1, title:'经营地址', val:'', key:'business_address', example:''},
  {id:1, title:'企业联系人', val:'', key:'contact_phone', example:''},
  {id:1, title:'联系人手机', val:'', key:'contact_phone', example:''},
  {id:7, title:'发布日期', val:'', key:'publishtime', example:''},
]
// 确认弹框
export const confirm = (msg:string, tip:string='温馨提示') =>{
// 引入 ElMessageBox
// ...原始代码...
  return ElMessageBox.confirm(msg, tip, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true
  })
}



